package com.meiya.hugegraph.util;

import java.util.List;

import org.apache.hugegraph.driver.HugeClient;
import org.apache.hugegraph.structure.graph.Edge;
import org.apache.hugegraph.structure.graph.Vertex;
import org.apache.hugegraph.structure.schema.EdgeLabel;
import org.apache.hugegraph.structure.schema.IndexLabel;
import org.apache.hugegraph.structure.schema.PropertyKey;
import org.apache.hugegraph.structure.schema.VertexLabel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HugeGraph工具类
 * 提供操作HugeGraph的常用方法
 */
public class HugeGraphUtil {

    private static final Logger logger = LoggerFactory.getLogger(HugeGraphUtil.class);

    /**
     * 清除图中所有数据和schema
     * 
     * @param client HugeGraph客户端
     */
    public static void clearAll(HugeClient client) {
        if (client == null) {
            logger.error("HugeClient不能为空");
            return;
        }
        
        logger.info("开始清除HugeGraph中的所有数据和结构...");
        
        try {
            // 1. 清除图中所有顶点和边
            clearGraphData(client);
            
            // 2. 清除所有索引
            clearSchema(client);
            
            logger.info("清除HugeGraph中的所有数据和结构完成");
        } catch (Exception e) {
            logger.error("清除HugeGraph数据失败", e);
            throw new RuntimeException("清除HugeGraph数据失败", e);
        }
    }
    
    /**
     * 清除图中所有的顶点和边数据
     * 
     * @param client HugeGraph客户端
     */
    public static void clearGraphData(HugeClient client) {
        if (client == null) {
            return;
        }
        
        logger.info("开始清除图数据...");
        
        try {
            // 1. 删除所有边
            List<Edge> edges = client.graph().listEdges();
            logger.info("准备删除{}条边", edges.size());
            for (Edge edge : edges) {
                client.graph().removeEdge(edge.id());
            }
            
            // 2. 删除所有顶点
            List<Vertex> vertices = client.graph().listVertices();
            logger.info("准备删除{}个顶点", vertices.size());
            for (Vertex vertex : vertices) {
                client.graph().removeVertex(vertex.id());
            }
            
            logger.info("图数据清除完成");
        } catch (Exception e) {
            logger.error("清除图数据失败", e);
            throw new RuntimeException("清除图数据失败", e);
        }
    }
    
    /**
     * 清除所有的schema定义，包括索引标签、边标签、顶点标签和属性键
     * 
     * @param client HugeGraph客户端
     */
    public static void clearSchema(HugeClient client) {
        if (client == null) {
            return;
        }
        
        logger.info("开始清除Schema...");
        
        try {
            // 必须按照依赖关系的逆序删除，即先删除依赖其他对象的对象
            // 1. 删除所有索引标签
            List<IndexLabel> indexLabels = client.schema().getIndexLabels();
            logger.info("准备删除{}个索引标签", indexLabels.size());
            for (IndexLabel indexLabel : indexLabels) {
                client.schema().indexLabel(indexLabel.name()).remove();
            }
            
            // 2. 删除所有边标签
            List<EdgeLabel> edgeLabels = client.schema().getEdgeLabels();
            logger.info("准备删除{}个边标签", edgeLabels.size());
            for (EdgeLabel edgeLabel : edgeLabels) {
                client.schema().edgeLabel(edgeLabel.name()).remove();
            }
            
            // 3. 删除所有顶点标签
            List<VertexLabel> vertexLabels = client.schema().getVertexLabels();
            logger.info("准备删除{}个顶点标签", vertexLabels.size());
            for (VertexLabel vertexLabel : vertexLabels) {
                client.schema().vertexLabel(vertexLabel.name()).remove();
            }
            
            // 4. 最后删除所有属性键
            List<PropertyKey> propertyKeys = client.schema().getPropertyKeys();
            logger.info("准备删除{}个属性键", propertyKeys.size());
            for (PropertyKey propertyKey : propertyKeys) {
                client.schema().propertyKey(propertyKey.name()).remove();
            }
            
            logger.info("Schema清除完成");
        } catch (Exception e) {
            logger.error("清除Schema失败", e);
            throw new RuntimeException("清除Schema失败", e);
        }
    }
    
    /**
     * 创建一个HugeClient实例
     * 
     * @param serverUrl HugeGraph服务器地址，例如：http://localhost:8080
     * @param graphName 图名称，例如：hugegraph
     * @return HugeClient实例
     */
    public static HugeClient createClient(String serverUrl, String graphName) {
        return HugeClient.builder(serverUrl, graphName)
                       .configTimeout(60) // 设置超时时间（秒）
                       .build();
    }
    
    /**
     * 安全关闭HugeClient
     * 
     * @param client HugeClient实例
     */
    public static void closeClient(HugeClient client) {
        if (client != null) {
            try {
                client.close();
                logger.info("HugeClient已关闭");
            } catch (Exception e) {
                logger.error("关闭HugeClient时发生错误", e);
            }
        }
    }
} 